import 'package:enterprise_v6_app/app/components/toast_widget.dart';
import 'package:enterprise_v6_app/app/core/constans/special_job_code.dart';
import 'package:enterprise_v6_app/app/core/http/http.dart';
import 'package:enterprise_v6_app/app/core/utils/interface.dart';
import 'package:enterprise_v6_app/app/data/entities/application/role_personnel_entity.dart';
import 'package:enterprise_v6_app/app/data/entities/application/special_list/process_list_entity.dart';
import 'package:enterprise_v6_app/app/data/entities/application/special_list/process_nodes_entity.dart';
import 'package:enterprise_v6_app/app/data/entities/application/ticket_plan_entity.dart';
import 'package:enterprise_v6_app/app/modules/application/special_operation/special_list/special_list_controller.dart';
import 'package:enterprise_v6_app/router/app_pages.dart';
import 'package:get/get.dart';

class ProcessAllocationApplyController extends GetxController {
  final specialListController = Get.find<SpecialListController>();

  // 流程模板数据
  late ProcessListEntity processListEntity;

  //小票数据
  late TicketPlanReceiptLists ticketPlanReceipt;

  //流程节点数据
  List<ProcessNodesEntity> nodeList = [];

  @override
  void onInit() {
    super.onInit();
    final Map<String, dynamic> argumentsMap = Get.arguments as Map<String, dynamic>;
    processListEntity = argumentsMap['processListEntity'] as ProcessListEntity;
    ticketPlanReceipt = argumentsMap['ticketPlanReceipt'] as TicketPlanReceiptLists;
    // 获取节点数据
    getNodeData();
  }

  /// 获取节点数据
  void getNodeData() async {
    final res =
        await HttpUtil().generateGetRequest<List<ProcessNodesEntity>>(Interface.getNode, queryParameters: {
      'processEncoding': processListEntity.processEncoding,
    }).execute(isShowLoading: true);

    res.onSuccess((result) {
      nodeList = result.data ?? [];
      //给固定节点添加参数
      for (var item in nodeList) {
        item.id = null;
        switch (item.appRoutingAddress) {
          //作业申请
          case SpecialJobCode.jobApplication:
            item.userTypeName = '申请人';
            item.userIds!.add(RolePersonnelEntity()
              ..nickName = ticketPlanReceipt.applyUserName
              ..userId = ticketPlanReceipt.applyUserId);
            item.startingCanChanged = false;
            break;
          //气体分析
          case SpecialJobCode.gasAnalysis:
            item.userTypeName = '气体分析人';
            item.startingCanChanged = true;
            break;
          //安全措施
          case SpecialJobCode.safetyMeasures:
            item.userTypeName = '监护人';
            addUserIds(item);
            item.startingCanChanged = false;
            break;
          //安全交底
          case SpecialJobCode.safetyDisclosure:
            item.userTypeName = '安全交底人';
            item.startingCanChanged = true;
            break;
          //作业审批
          case SpecialJobCode.jobApproval:
            item.userTypeName = '监护人';
            addUserIds(item);
            item.startingCanChanged = false;
            break;
          //作业关闭
          case SpecialJobCode.jobClose:
            item.userTypeName = '验收人';
            item.startingCanChanged = true;
            break;
          //其他自定义节点
          default:
            item.userTypeName = '执行人';
            item.startingCanChanged = true;
            break;
        }
      }
      update();
    });
  }

  // 添加监护人信息
  void addUserIds(ProcessNodesEntity entity) {
    for (var item in ticketPlanReceipt.guardianList) {
      entity.userIds!.add(RolePersonnelEntity()
        ..nickName = item.operatorUserName
        ..userId = item.operatorUserId);
    }
  }

  //选择人员
  void selectUser(ProcessNodesEntity item) {
    Get.toNamed(AppRoutes.personnelSelection, arguments: {
      'queryParameters': {'roleName': item.userTypeName},
      'isRadio': false,
    })?.then((value) {
      //如果不为空则设置人员信息
      if (value != null && value is List<RolePersonnelEntity>) {
        item.userIds!.clear();
        item.userIds!.addAll(value);
        Get.back();
      }
    });
  }

  // 跳转到作业申请
  Future<void> toApproval() async {
    if (processListEntity.businessType!.isEmpty) {
      AppToast.showWarning('流程部署失败,请在后台配置此流程业务类型！');
      return;
    }
    //设置业务id为小票id
    processListEntity.businessId = ticketPlanReceipt.id;
    processListEntity.id = null;
    //流程部署
    final res =
        await HttpUtil().generatePostRequest<List<ProcessNodesEntity>>(Interface.processArrange, data: {
      'rtCertificateField': processListEntity.toJson(),
      'processNodes': nodeList.map((e) => e.toJson()).toList(),
    }).execute(isShowLoading: true);
    //成功
    res.onSuccess((result) {
      Get.back();
      Get.back();
      specialListController.refreshPage();
      // 给小票数据添加
      ticketPlanReceipt.processEncoding = processListEntity.processEncoding;
      ticketPlanReceipt.type = 1;
      // 跳转到作业总页面类型和id
      Get.toNamed(AppRoutes.workAll, arguments: {
        'ticketBean': ticketPlanReceipt,
        'businessType': processListEntity.businessType,
      });
    });
    //失败
    res.onError((result) {
      AppToast.showWarning('流程部署失败');
    });
  }
}
